package daao_.dao;

import daao_.utils.Driuid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDAO<T> {
    private QueryRunner queryRunner=new QueryRunner();
    public int update(String sql,Object... parameters){
        Connection connection=null;
        try {
            connection=Driuid.getconnection();
            int update=queryRunner.update(connection,sql,parameters);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            Driuid.close(null,null,connection);
        }
    }


    public List<T> querymulti(String sql,Class<T> tClass,Object... parameters){
        Connection connection=null;
        try {
            connection=Driuid.getconnection();
            List<T> list=queryRunner.query(connection, sql,new BeanListHandler<>(tClass),parameters);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            Driuid.close(null,null,connection);
        }
    }


    public T querysingle(String sql,Class<T> tClass,Object... parameters){
        Connection connection=null;
        try {
            connection=Driuid.getconnection();
            T qs=queryRunner.query(connection, sql,new BeanHandler<>(tClass),parameters);
            return qs;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            Driuid.close(null,null,connection);
        }
    }

    public Object queryscalar(String sql,Object... parameters){
        Connection connection=null;
        try {
            connection=Driuid.getconnection();
            return queryRunner.query(connection, sql,new ScalarHandler(),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            Driuid.close(null,null,connection);
        }
    }
}
